import io

from PIL import Image
from i_home.utils.qiniuyun.qiniu_storage import _upload_to_qiniu


def compress_picture(img):
    _img = img.read()
    size = len(_img) / (1024 * 1024)  # 上传图片的大小 M单位
    image = Image.open(io.BytesIO(_img))
    if size > 1:
        # 压缩
        x, y = image.size
        im = image.resize((int(x / 1.73), int(y / 1.73)), Image.ANTIALIAS)  # 等比例压缩 1.73 倍
    else:
        # 不压缩
        im = image
    imgByteArr = io.BytesIO()
    im.save(imgByteArr, format='png')
    im = imgByteArr.getvalue()
    image_url, ret = _upload_to_qiniu(im)
    return image_url, ret
